package net.javacloud.service;

import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.delay.packet.DelayInformation;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.xdata.Form;
import org.jivesoftware.smackx.xdata.FormField;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Crowhyc on 2016/6/24.
 */
public class MucManager {
    static String roomId = "test003";
    static String nick = "小屋子";

    public static void main(String[] args) {
        MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(AccountRegister.getConnection());
        MultiUserChat muc = multiUserChatManager.getMultiUserChat(roomId + "@conference." + AccountRegister.getConnection().getServiceName());
        try {
            muc.create(nick);
            Form form = muc.getConfigurationForm();
            Form answerForm = form.createAnswerForm();
            for (FormField field : form.getFields()) {
                if (!FormField.Type.hidden.name().equals(field.getType()) && field.getVariable() != null) {
                    answerForm.setDefaultAnswer(field.getVariable());
                }
            }
            // 设置聊天室是持久聊天室，即将要被保存下来
            answerForm.setAnswer("muc#roomconfig_persistentroom", false);
            // 房间仅对成员开放
            answerForm.setAnswer("muc#roomconfig_membersonly", false);
            // 允许占有者邀请其他人
            answerForm.setAnswer("muc#roomconfig_allowinvites", true);
            // 能够发现占有者真实 JID 的角色
            // submitForm.setAnswer("muc#roomconfig_whois", "anyone");
            // 登录房间对话
            answerForm.setAnswer("muc#roomconfig_enablelogging", true);
            // 仅允许注册的昵称登录
            answerForm.setAnswer("x-muc#roomconfig_reservednick", false);
            // 允许使用者修改昵称
            answerForm.setAnswer("x-muc#roomconfig_canchangenick", false);
            // 允许用户注册房间
            answerForm.setAnswer("x-muc#roomconfig_registration", false);
            //房间最大人数
            List<String> list = new ArrayList<>();
            list.add("0");
            if (list.size() > 0) {
                answerForm.setAnswer("muc#roomconfig_maxusers", list);
            }
            muc.sendConfigurationForm(answerForm);
            muc.addMessageListener(msg -> {
                DelayInformation d = (DelayInformation) msg.getExtension("urn:xmpp:delay");
                //若是自己发送的消息，那stamp==null
                if (d != null) {
                    System.out.println(d.getStamp());
                }
            });
            muc.join(nick);
        } catch (XMPPException.XMPPErrorException | SmackException e) {
            e.printStackTrace();
        }

    }
}
